package cn.tingting.service.impl;

import cn.tingting.cilent.TentantCilent;
import cn.tingting.domain.Employee;
import cn.tingting.domain.LoginUser;
import cn.tingting.domain.Tenant;
import cn.tingting.dto.RegisterDto;
import cn.tingting.mapper.EmployeeMapper;
import cn.tingting.mapper.TenantMapper;
import cn.tingting.query.TenantQuery;
import cn.tingting.service.ITenantService;
import cn.tingting.util.AjaxResult;
import cn.tingting.util.PageList;
import cn.tingting.util.ValidUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ztt
 * @since 2021-03-02
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    @Autowired
    private TenantMapper mapper;
    @Autowired
    private TentantCilent cilent;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public PageList<Tenant> TenabtList(TenantQuery query) {
        Page<Tenant> page = new Page<Tenant>(query.getPage(),query.getRows());
        System.out.println(page);
        List<Tenant> date =  mapper.TenabtList(page,query);

        return new PageList<>(page.getTotal(),date);
    }

    @Override
    public void entering(RegisterDto dto) {
        //断言
        //ValidUtils.assertEuqal(dto.getComfirmPassword(),dto.getEmployee().getPassword(),"密码不一致");
        ValidUtils.assertNotNull(dto.getTenant().getCompanyName(),"公司名称不可为空");
        //先保存  loginUser
        LoginUser user = new LoginUser();
        user.setUsername(dto.getEmployee().getUsername());
        user.setPassword(dto.getEmployee().getPassword());
        user.setType(0);
        user.setMealId(dto.getMealId());
        AjaxResult ajaxResult = cilent.addOrUpdate(user);
        Date date = new Date();
        //判断是否成功  再保存  emp
        if(ajaxResult.isSuccess()){
            Long longinId = Long.valueOf(ajaxResult.getResultObj().toString());
            Employee employee = dto.getEmployee();
            employee.setRealName(dto.getEmployee().getUsername());
            employee.setInputTime(date);
            employee.setState(0);
            employee.setType(5);
            employee.setLoginId(longinId);
            employeeMapper.insert(employee);
            //保存tenant
            Tenant tenant = dto.getTenant();
            tenant.setRegisterTime(date);
            tenant.setAdminId(employee.getId());
            tenant.setState(0);
            mapper.insert(tenant);
            //使用机构组件
            employee.setTenantId(tenant.getId());
            employeeMapper.updateById(employee);
        }


    }
}
